<template>
  <div class="block-content-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft" type="text">返回</el-button>
        <div class="title-section">
          <h1 class="page-title">区块内容管理</h1>
          <p class="page-desc">管理区块"{{ blockInfo.name }}"的内容项</p>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd" icon="Plus">
          新增内容
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入内容标题" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getContentList" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 内容列表 -->
    <div class="content-table">
      <el-table :data="contentList" v-loading="loading" stripe>
        <!-- 动态字段列 -->
        <el-table-column
          v-for="field in displayFields"
          :key="field.name"
          :prop="field.name"
          :label="field.label"
          :min-width="getColumnWidth(field)"
          :show-overflow-tooltip="field.type === 'textarea' || field.type === 'editor'"
        >
          <template #default="{ row }">
            <div v-if="field.type === 'image' && getFieldValue(row, field.name)">
              <el-image
                :src="getFieldValue(row, field.name)"
                :alt="field.label"
                style="width: 60px; height: 40px; object-fit: cover;"
                :preview-src-list="[getFieldValue(row, field.name)]"
                fit="cover"
              />
            </div>
            <el-tag v-else-if="field.type === 'select'" size="small">
              {{ getFieldValue(row, field.name) }}
            </el-tag>
            <span v-else-if="field.type === 'textarea' || field.type === 'editor'">
              {{ truncateText(getFieldValue(row, field.name), 50) }}
            </span>
            <span v-else>
              {{ getFieldValue(row, field.name) }}
            </span>
          </template>
        </el-table-column>

        <!-- 固定的系统字段 -->
        <el-table-column prop="orderNum" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" text @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getContentList"
          @current-change="getContentList"
        />
      </div>
    </div>

    <!-- 内容编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="resetForm"
    >
      <!-- 动态表单 -->
      <DynamicForm
        ref="dynamicFormRef"
        :block-id="blockInfo.id"
        v-model="form"
        @configure-fields="handleConfigureFields"
      />

      <!-- 通用字段 -->
      <el-form label-width="120px" style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input-number v-model="form.orderNum" :min="0" placeholder="排序号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus, Search, Refresh } from '@element-plus/icons-vue'
import { blockApi } from '@/api/block'
import DynamicForm from '@/components/DynamicForm.vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const fieldsLoading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const dynamicFormRef = ref()

// 区块字段配置
const blockFields = ref([])

// 区块信息
const blockInfo = ref({
  id: route.params.id as string, // 保持字符串格式，避免精度丢失
  name: '',
  alias: '',
  description: ''
})

// 搜索表单
const searchForm = ref({
  title: '',
  status: undefined
})

// 内容列表
const contentList = ref([])

// 分页信息
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 表单数据
const form = ref({
  id: null,
  blockId: null,
  orderNum: 999,
  status: 1
})

// 表单验证规则（动态表单自己处理验证）

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑内容' : '新增内容')

// 计算属性 - 显示在表格中的字段
const displayFields = computed(() => {
  // 过滤出需要在列表中显示的字段（排除一些不适合在表格中显示的字段类型）
  return blockFields.value.filter(field => {
    // 排除富文本编辑器等不适合在表格中显示的字段
    const excludeTypes = ['editor']
    return !excludeTypes.includes(field.type) && field.status === 1
  }).sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0))
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取字段值（处理attributes中的动态字段）
const getFieldValue = (row, fieldName) => {
  // 固定字段列表（使用后端返回的字段名）
  const fixedFields = ['title', 'subtitle', 'summary', 'content', 'imageUrl', 'linkUrl', 'target', 'orderNum', 'status', 'createDate', 'updateDate']

  // 处理字段名映射：前端显示名 -> 后端字段名
  let actualFieldName = fieldName
  if (fieldName === 'image') {
    actualFieldName = 'imageUrl'
  } else if (fieldName === 'link') {
    actualFieldName = 'linkUrl'
  }

  // 调试日志
  if (fieldName === 'image' || fieldName === 'link') {
    console.log(`获取字段值: ${fieldName} -> ${actualFieldName}, 值: ${row[actualFieldName]}`)
  }

  if (fixedFields.includes(actualFieldName)) {
    return row[actualFieldName] || ''
  } else {
    // 动态字段从attributes中获取
    if (row.attributes) {
      let attributes = row.attributes
      if (typeof attributes === 'string') {
        try {
          attributes = JSON.parse(attributes)
        } catch (e) {
          console.warn('解析attributes失败:', e)
          return ''
        }
      }
      return attributes[fieldName] || ''
    }
    return ''
  }
}

// 获取列宽度
const getColumnWidth = (field) => {
  switch (field.type) {
    case 'image':
      return 100
    case 'select':
    case 'radio':
      return 120
    case 'textarea':
      return 200
    case 'editor':
      return 250
    default:
      return 150
  }
}

// 截断文本
const truncateText = (text, maxLength = 50) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 获取区块信息
const getBlockInfo = async () => {
  try {
    const response = await blockApi.getInfo(blockInfo.value.id)
    if (response.code === 0) {
      blockInfo.value = response.data
    } else {
      ElMessage.error(response.msg || '获取区块信息失败')
    }
  } catch (error) {
    console.error('获取区块信息失败:', error)
    ElMessage.error('获取区块信息失败')
  }
}

// 获取区块字段配置
const getBlockFields = async () => {
  fieldsLoading.value = true
  try {
    console.log('加载区块字段配置:', blockInfo.value.id)
    const response = await blockApi.getFields(blockInfo.value.id)
    console.log('字段配置响应:', response)

    if (response.code === 0) {
      blockFields.value = response.data || []
      console.log('加载的字段配置:', blockFields.value)
    } else {
      console.warn('获取字段配置失败:', response.msg)
      blockFields.value = []
    }
  } catch (error) {
    console.error('获取字段配置失败:', error)
    blockFields.value = []
  } finally {
    fieldsLoading.value = false
  }
}

// 获取内容列表
const getContentList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      title: searchForm.value.title,
      status: searchForm.value.status
    }

    const response = await blockApi.getContentList(blockInfo.value.id, params)
    if (response.code === 0) {
      contentList.value = response.data.list || []
      pagination.value.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取内容列表失败')
    }
  } catch (error) {
    console.error('获取内容列表失败:', error)
    ElMessage.error('获取内容列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    status: undefined
  }
  getContentList()
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除内容"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await blockApi.deleteContent(blockInfo.value.id, row.id)
      if (response.code === 0) {
        ElMessage.success('删除成功')
        getContentList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除内容失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: any) => {
  try {
    const response = await blockApi.updateContentStatus(blockInfo.value.id, row.id, row.status)
    if (response.code === 0) {
      ElMessage.success('状态更新成功')
    } else {
      ElMessage.error(response.msg || '状态更新失败')
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!dynamicFormRef.value) return

  try {
    // 验证动态表单
    const isValid = await dynamicFormRef.value.validate()
    if (!isValid) return

    submitting.value = true

    // 获取格式化的表单数据
    const formattedData = dynamicFormRef.value.getFormattedData()

    // 合并通用字段
    const submitData = {
      ...formattedData,
      orderNum: form.value.orderNum,
      status: form.value.status
    }

    if (isEdit.value) {
      submitData.id = form.value.id
    }

    console.log('提交的数据:', submitData)
    console.log('格式化后的数据:', formattedData)

    const response = isEdit.value
      ? await blockApi.updateContent(blockInfo.value.id, submitData)
      : await blockApi.createContent(blockInfo.value.id, submitData)

    if (response.code === 0) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      getContentList()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    blockId: null,
    orderNum: 999,
    status: 1
  }
  dynamicFormRef.value?.resetFields()
}

// 配置字段
const handleConfigureFields = () => {
  router.push(`/content/block/field-config?blockId=${blockInfo.value.id}`)
}

onMounted(async () => {
  await getBlockInfo()
  await getBlockFields() // 加载字段配置
  getContentList()
})
</script>

<style scoped lang="scss">
.block-content-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .title-section {
        .page-title {
          font-size: 20px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 4px 0;
        }

        .page-desc {
          font-size: 13px;
          color: #909399;
          margin: 0;
        }
      }
    }
  }

  .search-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .content-table {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
